package com.hzit.manager.excep;

import com.hzit.common.utils.R;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类名：
 * 作者：WF
 * 功能：
 */
// @ControllerAdvice
// @ResponseBody
@RestControllerAdvice(basePackages = "com.hzit.manager.controller")
public class MyExceptionHandler {

	@ExceptionHandler({MethodArgumentNotValidException.class})
	public R errorHandler(MethodArgumentNotValidException ex) {

		//1. 获取所有的字段错误
		BindingResult result = ex.getBindingResult();
		List<FieldError> fieldErrors = result.getFieldErrors();
		//2. 定义放错误信息的map中
		Map<String, String> errors = new HashMap<>();
		for (FieldError fieldError : fieldErrors) {
			String field = fieldError.getField();
			String message = fieldError.getDefaultMessage();
			errors.put(field, message);
		}
		return R.error().put("errors", errors);
	}

	@ExceptionHandler({MyException.class})
	public R error(MyException ex, HttpServletResponse response){
		String message = "未知异常！";
		if(ex != null ){
			message = ex.getMessage();
		}
		String code = ex.getCode();
		//输出指定的状态码
		response.setStatus(new Integer(code));
		return R.error(message);
	}
}
